package com.jintian.smart.kernel.flowable.component;

import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.beanutils.PropertyUtils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class StringRender implements ApplicationContextAware {
	protected ApplicationContext applicationContext;
	private static Pattern patten = Pattern.compile("(\\$\\{[^\\$\\{\\}]*\\})+");

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		this.applicationContext = applicationContext;
	}

	protected String format(String template, Map<String, Object> variants) throws Exception {
		Matcher matcher = patten.matcher(template);
		StringBuffer sb = new StringBuffer();
		int start = 0;
		while (matcher.find()) {
			String group = matcher.group();
			String beanName = group.substring(2, group.indexOf("."));
			String prop = group.substring(group.indexOf(".") + 1, group.length() - 1);
			Object bean = variants.get(beanName);
			Object value = PropertyUtils.getProperty(bean, prop);
			sb.append(template.substring(start, matcher.start())).append(value);
			start = matcher.end();
		}
		sb.append(template.substring(start));
		return sb.toString();
	}
}
